package com.shanzmoo.db.trade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.PayStatusConstant;
import com.shanzmoo.db.trade.entity.PayOrderBodyEntity;
import com.shanzmoo.db.trade.entity.PayOrderEntity;
import com.shanzmoo.db.trade.mapper.PayOrderMapper;
import com.shanzmoo.db.trade.service.IPayOrderBodyService;
import com.shanzmoo.db.trade.service.IPayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 支付订单 服务实现类
 * </p>
 *
 * @author Gzhao
 * @since 2020-12-09
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrderEntity> implements IPayOrderService {

    @Autowired
    private IPayOrderBodyService payOrderBodyService;

    @Override
    public SResponse<Boolean> updatePaySuccessStatus(PayOrderEntity payOrderEntity, LocalDateTime finishTime) {
        payOrderEntity.setPayStatus(PayStatusConstant.PAY_SUCCESS);
        payOrderEntity.setFinishTime(finishTime);

        return SResponse.ok(baseMapper.updateById(payOrderEntity) == 1);
    }

    @Override
    public PayOrderEntity getByPayNo(String payNo) {
        return baseMapper.selectOne(
                new QueryWrapper<PayOrderEntity>()
                        .eq("deleted", false)
                        .eq("pay_no", payNo)
        );
    }

    @Override
    public SResponse<Boolean> updatePaySuccessStatusByNo(String payNo) {
        PayOrderEntity payOrderEntity = this.getByPayNo(payNo);
        return this.updatePaySuccessStatus(payOrderEntity, LocalDateTime.now());
    }

    @Override
    public void updateByPayQuery(PayOrderEntity payOrder, PayOrderBodyEntity payOrderBody) {
        baseMapper.updateById(payOrder);

        payOrderBodyService.updateById(payOrderBody);
    }

    @Override
    public PayOrderEntity saveOrder(PayOrderEntity payOrderEntity, PayOrderBodyEntity payOrderBody) {
        baseMapper.insert(payOrderEntity);
        payOrderBodyService.save(payOrderBody);

        return payOrderEntity;
    }

    @Override
    public void updateQueryTimes(String payNo) {
        baseMapper.updateQueryTimes(payNo);
    }
}
